package org.iweb.ioc;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.iweb.register.RegisterFactory;

@SuppressWarnings({ "unchecked" })
public class ServiceLookup {

	private static ServiceLookup instance;
	
	private ServiceLookup(){
		
	}
	
	public Object get(String id){
		
		BeanObj obj=getRegister().getInstances().get(id);
		
		Object result=null;
		
		if(obj!=null){
			
			if(obj.getObj()==null){				
				try {
					//result=instance.getClass().getClassLoader().loadClass(obj.getClazz().getName()).newInstance();
					result=obj.getClazz().newInstance();
				
					Method[] methods= obj.getClazz().getMethods();
					
					for(Method m: methods){
						Inject ann=m.getAnnotation(Inject.class);
						if(ann!=null){						
							m.invoke(result, get(ann.id()));
						}
					}
					
					if(!obj.getInitMethod().isEmpty()){
						Method m=obj.getClazz().getMethod(obj.getInitMethod(), null);
						m.invoke(result, null);
					}
					
				} catch (InstantiationException | IllegalAccessException
						| IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
					e.printStackTrace();
				}
				
				if(obj.isSingleton())
					obj.setObj(result);
			}else{
				result=obj.getObj();
			}
		}
		
		return result;
	}
	
	

	public static ServiceLookup getInstance() {
		if(instance==null)
			instance=new ServiceLookup();
		return instance;
	}

	public IocRegister getRegister() {
		return (IocRegister) RegisterFactory.getInstance().getRegisterByName("IocRegister");
	}
	
}
